<template>
  <div>
    <!-- 面包屑 -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/transportation-maintenance-approval',
          }"
          >结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/settlement-management/transportation-maintenance-approval',
          }"
          >运输结算管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: breadUrl,
          }"
          >结算单维护</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">新增结算单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs v-model="activeName" class="el-tabs__customize">
          <el-tab-pane label="基本信息" name="first">
            <baseInfo
              ref="baseInfo"
              :detail="detailInfo"
              :myId="myId"
              :settlementForm="settlementForm"
              :settlementList="settlementList"
              @updataList="updataList"
              :file-list="fileList"
              showSummary
            />
          </el-tab-pane>

          <el-tab-pane label="结算单明细" name="second">
            <keep-alive>
              <financeInfo
                ref="financeInfo"
                :detail="detailInfo"
                :settlementList="settlementList"
                :settlementForm="settlementForm"
                @numrows="numrows"
                @delrows="delrows"
              />
            </keep-alive>
          </el-tab-pane>

          <el-tab-pane label="附件" name="fouth" class="file-group">
            <fileInfo ref="fileInfo" v-model="fileList"></fileInfo>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button type="bottom" icon="icon-ccui-save" @click="saveStorage"
            >暂存</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-export"
            @click="submitHandle(1)"
            >保存并提交</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import jsList from "../js";
import baseInfo from "./baseInfo";
import financeInfo from "./financeInfo";
import fileInfo from "@/basa/components/public/uploadInfo3";

import {
  // getSettlementById,
  // getSmpPcConcById,
  saveSettlement,
  tsSettlement,
  // submitSettlement
  // selectSettlementCount
} from "../api/transportation-approval";
import Bus from "./bus";
export default {
  props: {
    state: {
      type: String,
      default: "create",
    },
  },
  components: {
    baseInfo,
    financeInfo,
    fileInfo,
  },
  inject: ["reload"],
  data() {
    return {
      settlementForm: {
        duration: [],
        contractId: null,
        pcConcId: "", // 基础合同id
        scConcId: "", // 结算申请单id
        contractName: "", // 合同名称
        contractCode: "", // 合同编号
        partyAName: "", // 合同甲方
        partyBId: "", // 合同乙方id
        partyBName: "", // 合同乙方
        supplierName: "", //供应商
        taxRatePercent: "", // 税率
        nowTotalContractPriceIncludeTax: "", // 合同金额（含税）
        settleTotalAmtIncludeTax: "", // 开累结算金额（含税）
        payedTotalAmtIncludeTax: "", // 开累支付金额
        currSetCount: 0, // 结算数量
        currSetMoney: 0, // 结算金额
        contractBalance: "", // 合同余额（含税）
        settlementNum: "", // 结算单编号
        settlementPeriod: "", // 结算期次
        currentSettlePayAmtIncludeTax: "", // 本期支付金额
        currentSettleAmtIncludeTax: "", // 本期结算金额（含税）
        currentSettleUnpayAmtIncludeTax: "", // 本期结算未支付金额（含税）
        paymentNum: "", // 支付单编号
        compiler: "", // 编制人
        compilerId: "", // 编制人id
        paymentApplyDate: "", // 支付申请日期
        remarks: "", // 备注
        reportInOrgName: "",
        reportInOrgId: "",
        reportUsername: "",
        reportOpenid: "",
        reportTime: "",
        transportCategoryCode: "", // 运输类别编码
        transportCategoryName: "", // 运输类别名称
        contractCode2: "", // 当合同值改变时记忆上一次的合同编号
        settlementStart: "",
        settlementEnd: "",
      },
      showFileList: true,
      fileList: [],
      files: [],
      jsList,
      breadcrumbLastItem: "结算单",
      activeName: "first",
      isTrue: true,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      myId: "",
      tabBtn: [
        { label: "基本信息", value: "baseInfo" },
        { label: "财务信息", value: "financeInfo" },
        { label: "采购清单", value: "purchaseList" },
      ],
      summaryArr: ["subContractorsName"],
      tableTheadOptions: [
        {
          label: "合同编号",
          prop: "subContractName",
          width1: 120,
        },
        {
          label: "合同名称",
          prop: "subContractorsName",
        },
      ],
      oneLineTableData: [
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
        { subContractName: 1, subContractorsName: 1 },
      ],
      arr1: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" },
        { id: 3, name: "cc" },
      ],
      arr2: [
        { id: 1, name: "aa" },
        { id: 2, name: "bb" },
      ],
      a: [],
      settlementList: [],
      settlementListPur: [],
      acceptCountNumber: [], //验收单明细验收数量临时存值
      breadUrl: "",
    };
  },
  created() {
    if (this.isTz == 1) {
      this.breadItem = "结算单台账";
      this.breadUrl = "/settlement-management/transportation-standing-book";
    } else {
      this.breadItem = "结算单维护";
      this.breadUrl =
        "/settlement-management/transportation-maintenance-approval";
    }
    let a = [...this.arr1];
    for (let i = 0; i < this.arr1.length; i++) {
      let flag = false;
      for (let j = 0; j < this.arr2.length; j++) {
        if (this.arr1[i].id === this.arr2[j].id) flag = true;
      }
      if (flag)
        a.splice(
          a.findIndex((_) => _.id === this.arr1[i].id),
          1
        );
    }
  },
  mounted() {
    Bus.$on("borthsettlementList", () => {
      this.settlementList = []; // 当合同改变时，结算单明细清空
    });
  },
  destroyed() {
    Bus.$off("borthsettlementList");
  },
  activated() {},
  deactivated() {},
  methods: {
    updataList(val) {
      this.settlementList = val;
      this.$refs.financeInfo.acceptForm = [];
    },
    handleFilesParams() {
      let gistUploadIds = [],
        otherUploadIds = [];
      this.fileList.map((e, i) => {
        if (e.fileType == 51) {
          gistUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.createTime,
          });
        } else {
          otherUploadIds.push({
            fileDesc: e.fileDesc,
            sn: i,
            uploadId: e.uploadId,
            uploadTime: e.createTime,
          });
        }
      });
      return {
        gistUploadIds: gistUploadIds,
        otherUploadIds: otherUploadIds,
      };
    },
    // 暂存
    saveStorage() {
      this.settlementList.forEach((item, index) => {
        item.sn = index;
        if (item.acceptanceCode != undefined) {
          item.acceptCode = item.acceptanceCode;
        }
      });
      this.$refs.baseInfo.settlementForm.billSource = "20";
      let params = {
        settlementBO: this.$refs.baseInfo.settlementForm,
        settlementBOList: this.settlementList,
        gistUploadIds: this.handleFilesParams().gistUploadIds,
        otherUploadIds: this.handleFilesParams().otherUploadIds,
      };
      this.$loading({
        lock: true,
        text: "暂存中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      tsSettlement(params)
        .then((res) => {
          this.$loading().close();
          if (res.data.code == "0") {
            this.$message({
              type: "success",
              message: "暂存成功",
            });
            this.handleBack();
          }
        })
        .catch((e) => {
          this.$loading().close();
        });
    },
    // 保存 提交
    submitHandle(operType) {
      // 校验弹窗
      if (
        !this.settlementForm.settlementStart ||
        !this.settlementForm.settlementEnd ||
        this.settlementForm.settlementName == "" ||
        this.settlementForm.settlementName == undefined ||
        this.settlementForm.contractCode == "" 
        // this.settlementForm.currSetMoney == ""
      ) {
        this.$message({
          type: "error",
          message: "请输入必填项",
          ccuiCustom: true,
          duration: 1500,
        });
        this.activeName = "first";
      } else {
        if(this.settlementList.length <= 0) {
          this.$message({
            type: "error",
            message: "结算单明细不能为空，请选择合同物资",
            ccuiCustom: true,
            duration: 1500,
          });
          this.activeName = "second";
          return;
        }
        let settlementCountBool = this.settlementList.every(
          (item) => item.settlementCount != 0 && item.settlementCount != ""
        );
        if (!settlementCountBool) {
          this.$message.warning("结算数量不能为空/0");
          this.activeName = "second";
          return;
        }

        let isOtherCostZero = this.settlementList.every(
          (item) => item.unitPriceWithTax != "" && item.unitPriceWithTax != 0
        );
        if (!isOtherCostZero) {
          this.$message.warning("单价不能为空/0");
          this.activeName = "second";
          return;
        }
      }
      this.handleSaveData(operType);
    },
    handleSaveData(operType) {
      this.$refs.baseInfo.handleSubmit().then((form) => {
        form.materialSource = form.smpPcConc.materialSource;
        form.billSource = "20";
        this.fileList.forEach((row) => {
          row.fileInfoId = row.uploadId;
          row.uploadTime = new Date(row.createTime).getTime();
        });

        if (operType == 0) {
          this.$loading({
            lock: true,
            text: "保存中,请稍后...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          saveSettlement({
            settlementBO: form,
            gistUploadIds: this.handleFilesParams().gistUploadIds,
            otherUploadIds: this.handleFilesParams().otherUploadIds,
            settlementBOList: this.settlementList,
            operType: 0, // 0保存，1提交
          })
            .then((res) => {
              this.$loading().close();
              if (res.data.code == "0") {
                this.$message({
                  type: "success",
                  message: "保存并校验成功",
                });
                this.handleBack();
              }
            })
            .catch((e) => {
              this.$loading().close();
            });
        } else {
          this.$loading({
            lock: true,
            text: "提交中,请稍后...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          saveSettlement({
            settlementBO: form,
            gistUploadIds: this.handleFilesParams().gistUploadIds,
            otherUploadIds: this.handleFilesParams().otherUploadIds,
            settlementBOList: this.settlementList,
            operType: 1, // 0保存，1提交
          })
            .then((res) => {
              this.$loading().close();
              if (res.data.code == "0") {
                this.$message({
                  type: "success",
                  message: "保存并提交成功",
                });
                this.handleBack();
              }
            })
            .catch((e) => {
              this.$loading().close();
              console.log(e);
            });
        }
      });
    },

    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "/settlement-management/transportation-maintenance-approval/transportation-maintenance-all"
      );
      this.reload();
    },
    delrows(row) {},
    numrows(row) {
      this.settlementList = row;
    },
  },
};
</script>
<style lang="scss" scoped>
/deep/ .file-group .el-group-title .group-content {
  margin-top: 40px;
}
/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
  top: 0;
  display: flex;
}
/deep/
  .el-group-title.ccui-group-wrapper
  .extend-btn
  div:nth-child(1)
  .el-upload {
  margin-right: 10px;
}
/deep/ .el-tabs__customize {
  padding-bottom: 50px;
}
</style>
